﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SMEXAUDIOLib;
using System.IO;
using System.Configuration;

namespace AudioCtrl
{
    public class AudioLib
    {
        private SmAudioClass _audioClass;
        private string _fileName, _dstPath;
        private string _targetPath;

        public int position
        {
            get { return _audioClass.SoundPosition; }
        }

        public int length
        {
            get { return _audioClass.SoundLength; }
        }

        public bool fileLoaded
        {
            get { return _audioClass.State != SmXAudioState.smxNoSoundFile; }
        }

        public string targetFilePath
        {
            get { return _targetPath; }
        }

        public string recordMode
        {
            get
            {
                if (_audioClass.RecordMode == SmXRecordMode.smxInsert)
                    return "Insert";
                else
                    if (_audioClass.RecordMode == SmXRecordMode.smxOverwrite)
                        return "Overwrite";
                    else
                        return "Error";
            }
        }

        public void setRecordMode()
        {
            if (_audioClass.RecordMode == SmXRecordMode.smxInsert)
                _audioClass.RecordMode = SmXRecordMode.smxOverwrite;
            else
                if (_audioClass.RecordMode == SmXRecordMode.smxOverwrite)
                    _audioClass.RecordMode = SmXRecordMode.smxInsert;
        }

        public AudioLib()
        {
            _dstPath = string.Empty;
            _audioClass = new SmAudioClass();
            _audioClass.Initialize();
            _audioClass.WindingSpeed = 10;
        }

        public bool LoadFile(string filePath, bool savePrevious)
        {
            //using (new Impersonator(ConfigurationManager.AppSettings["ServerUser"].ToString(), ConfigurationManager.AppSettings["ServerName"].ToString(), "MedSoft01"))
            //{
                bool success = true;
                if (_audioClass.State != SmXAudioState.smxNoSoundFile)
                {
                    if (savePrevious)
                    {
                        _audioClass.SaveFile();
                        _audioClass.CloseFile();
                    }
                    else
                        _audioClass.CloseFile();
                }

                if (File.Exists(filePath))
                {
                    try
                    {
                        _audioClass.OpenFile(filePath);
                        _audioClass.SoundPosition = _audioClass.SoundLength - 1;
                        _dstPath = filePath;
                        _targetPath = filePath;
                    }
                    catch (Exception ex)
                    {
                        string message = ex.Message;
                    }
                }
                else
                {
                    success = false;
                }
                return success;
            //}
        }

        public void CreateFile(string[] parameters, bool savePrevious)
        {
            if (_audioClass.State != SmXAudioState.smxNoSoundFile)
            {
                if (savePrevious)
                    _audioClass.SaveFile();
                else
                    _audioClass.CloseFile();
            }

            _audioClass.AudioFormat = SmXAudioFormat.smxGSM610_8kHzMono;

            _targetPath = ConfigurationManager.AppSettings["ServerFileSystem"].ToString() + DateTime.Now.Year.ToString() + "\\" + parameters[2] + "\\" + parameters[4];

            _audioClass.NewFile();

            if (String.IsNullOrEmpty(parameters[0]))
            {
                _fileName = Guid.NewGuid().ToString();
            }
            else
            {
                _fileName = parameters[0];
            }

            _fileName = _fileName + ".wav";
            _targetPath = _targetPath + "\\" + _fileName;
        }

        public void CloseFile()
        {
            if (_audioClass.State != SmXAudioState.smxNoSoundFile)
            {
                _audioClass.CloseFile();
                _dstPath = string.Empty;
            }
        }

        public void Play()
        {
            if (_audioClass.State != SmXAudioState.smxNoSoundFile)
            {
                if (_audioClass.State != SmXAudioState.smxPlayback)
                    _audioClass.Play();
                else
                    _audioClass.Stop();
            }
        }

        public void Record()
        {
            if (_audioClass.State != SmXAudioState.smxNoSoundFile)
            {
                if (_audioClass.State != SmXAudioState.smxRecord)
                {
                    _audioClass.Record();
                }
                else
                {
                    _audioClass.Stop();
                }
            }
        }

        public bool IsRecording
        {
            get { return _audioClass.State == SmXAudioState.smxRecord; }
        }

        public bool IsPlaying
        {
            get { return _audioClass.State == SmXAudioState.smxPlayback; }
        }

        public void FForward()
        {
            if (_audioClass.State != SmXAudioState.smxNoSoundFile)
            {
                _audioClass.FastForward();
            }
        }

        public void FRewind()
        {
            if (_audioClass.State != SmXAudioState.smxNoSoundFile)
            {
                _audioClass.FastRewind();
            }
        }

        public void Stop()
        {
            if (_audioClass.State != SmXAudioState.smxNoSoundFile)
            {
                _audioClass.Stop();
            }
        }

        public void Pause()
        {
            if (_audioClass.State != SmXAudioState.smxNoSoundFile)
            {
                if (_audioClass.State == SmXAudioState.smxRecord)
                    _audioClass.RecordPause();
                if (_audioClass.State == SmXAudioState.smxPlayback)
                    _audioClass.Stop();
            }
        }

        public void GoToStart()
        {
            _audioClass.SoundPosition = 0;
        }

        public bool SaveNewFile()
        {
            //using (new Impersonator(ConfigurationManager.AppSettings["ServerUser"].ToString(), ConfigurationManager.AppSettings["ServerName"].ToString(), "MedSoft01"))
            //{
                bool IsEmpty = true;
                if (_audioClass.FileModified)
                {
                    IsEmpty = false;
                    if (String.IsNullOrEmpty(_audioClass.FileName))
                    {
                        string AppFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\" + ConfigurationManager.AppSettings["LocalPath"].ToString();
                        if (!Directory.Exists(AppFolder))
                        {
                            Directory.CreateDirectory(AppFolder);
                        }
                        string fullPath = AppFolder + "\\" + _fileName;
                        try
                        {
                            _audioClass.SaveFileAs(fullPath);
                            _audioClass.CloseFile();
                            try
                            {
                                string onlyPath = _targetPath.Substring(0, _targetPath.LastIndexOf("\\") + 1);
                                if (!File.Exists(onlyPath))
                                {
                                    Directory.CreateDirectory(onlyPath);
                                }

                                File.Copy(fullPath, _targetPath);
                                File.Delete(fullPath);
                            }
                            catch (Exception ServerException)
                            {
                                throw ServerException;
                            }
                        }
                        catch (Exception e)
                        {
                            throw e;
                        }
                    }
                    else
                    {
                        try
                        {
                            _audioClass.SaveFile();
                            _audioClass.CloseFile();
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                }
                _audioClass.CloseFile();
                return IsEmpty;
            //}
        }

        public int SpeakerVolume
        {
            get { return _audioClass.GlobalWaveVolume; }
            set { _audioClass.GlobalWaveVolume = value; }
        }

        public int MicVolume
        {
            get { return _audioClass.VORLevel; }
            set { _audioClass.VORLevel = value; }
        }
    }
}